import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: '登录',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/main',
    name: '首页',
    component: () => import('@/views/Main.vue'),
    children:[
      {
        path:'administrators',
        name:'管理员',
        meta: {
          parent:'系统管理',
          permissions: ['admin.role.read']
        },
        component: () => import('@/views/system/Administrators')
      },
      {
        path:'role',
        name:'角色管理',
        meta: {
          parent:'系统管理',
          permissions: ['admin.user.read']
        },
        component: () => import('@/views/system/Role.vue')
      },
      {
        path:'shopList',
        name:"分类管理",
        meta: {
          parent:'商品管理',
          permissions: ['shop.category.read']
        },
        component: () => import('@/views/shop/shopList.vue')
      },
      {
        path:'product',
        name:"产品管理",
        meta: {
          parent:'商品管理',
          permissions: ['shop.product.read']
        },
        component: () => import('@/views/shop/onProduct.vue')
      },
      {
        path:'sale',
        name:"上架下架",
        meta: {
          parent:'商品管理',
          permissions: ['shop.sale.read']
        },
        component: () => import('@/views/shop/sale.vue')
      },
      {
        path:'current',
        name:"备餐配餐",
        meta: {
          parent:'订单管理',
          permissions: ['sale.order.current']
        },
        component: () => import('@/views/order/Current.vue')
      },
      {
        path:'history',
        name:"历史订单",
        meta: {
          parent:'订单管理',
          permissions: ['sale.order.history']
        },
        component: () => import('@/views/order/History.vue')
      }
    ]
  },
  {
    path:'*',
    component:() => import('../views/404.vue')
  }
]


const router = new VueRouter({
  routes
})


router.beforeEach( async(to, from, next) => {
  nprogress.start()
  const { path } = to;
  if(!document.cookie.includes('seec_shop')) {
    // 未登录
    if(path === '/login') {
      next()
    } else {
      next('/login?redirect='+path)
    }
    return;
  }
  // 已登录
  if(path === '/login') return next();
  if(path === '/') return next('/main');
  if(path.startsWith('/main/')) {
    if(!store.getters.isWho) {
      console.log(1);
      const isGet = await store.dispatch('getWho');
      console.log(2, isGet);
    }

    if(!to.meta || !to.meta.permissions) {
      next()
    } else {
      const pass = to.meta.permissions.some(p => store.getters.permissions.includes(p));
      pass ? next() : next('/404')
    }
    return;
  }
  next()
})

router.afterEach((to) => {
  nprogress.done()
  document.title = to.name
  window.scrollTo(0,0)
})

export default router
